<script setup lang="tsx">
import { computed, nextTick, ref, watch } from 'vue';
import { SimpleScrollbar } from '@sa/materials';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions, menuIconTypeOptions, menuTypeOptions } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { getLocalIcons } from '@/utils/icon';
import { fetchGetAllRoles } from '@/service/api';
import { ApiMenuInput, ApiMenuItem, ApimenuserviceApi, ApiSysDataConfigInput, ApiSysDataConfigOut, MenuOpenType, PgType } from '@/api-services';
import { NetoKit } from '@/typings/neto';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { SysdataconfigApi } from '@/api-services/apis/sysdataconfig-api';

defineOptions({
  name: 'ConfigOperateModal'
});

export type OperateType = UI.TableOperateType | 'addChild';

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: ApiSysDataConfigOut | null;
  /** all pages */
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation} = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    //添加配置项
    add: $t('page.manage.sysConfig.addTitle'),
    //添加子配置项
    addChild: $t('page.manage.sysConfig.addChildTitle'),
    //修改配置项
    edit: $t('page.manage.sysConfig.editTitle')
  };
  return titles[props.operateType];
});


type Model = NetoKit.IsNonNullable<ApiSysDataConfigInput>;

const model = ref(createDefaultModel());


function createDefaultModel(): Model {
  return {
    id: 0,
    pId: 0,
    name: '',
    value: '',
    valueEx: '',
    groupName: '',
    isEnable: true,
    remark: '',
    level: 0,
    levelPath: '',
    key: '',
    pKey: '',
    sort: 0
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'pId' | 'key' | 'groupName'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  pId: defaultRequiredRule,
  name: defaultRequiredRule,
  key: defaultRequiredRule,
  groupName: defaultRequiredRule
};






async function handleInitModel() {
  //初始化默认model
  model.value = createDefaultModel();

  if (!props.rowData) return;

  await nextTick();

  if (props.operateType === 'addChild') {
    const { id, groupName, key } = props.rowData;

    Object.assign(model.value, { pid: id, groupName: groupName, pKey: key });
    // model.value.pId=id!;
    // model.value.groupName=groupName!;
    // model.value.pKey=key!;


    console.log(model.value, { id, groupName, key })
  }

  if (props.operateType === 'edit') {
    const { ...rest } = props.rowData;
    Object.assign(model.value, rest);
  }



}

function closeModal() {
  visible.value = false;
}



async function handleSubmit() {
  await validate();


  //判断是哪一种操作
  switch (props.operateType) {
    case 'add':
      await add();
      break;
    case 'addChild':
      await add();
      break;
    case 'edit':
      await update();
      break;
  }

  // request
  emit('submitted');
}
async function add() {
  const [err, res] = await feature(getAPI(SysdataconfigApi).insert(model.value));
  queryDone(err, () => {
    if (res?.data.data) {
      window.$message?.success($t('common.success'));
      closeModal();

    } else {
      window.$message?.error($t('common.failed'));

    }
  });
}
async function update() {
  const [err, res] = await feature(getAPI(SysdataconfigApi).update(model.value));
  queryDone(err, () => {
    if (res?.data.data) {
      window.$message?.success($t('common.success'));
      closeModal();

    } else {
      window.$message?.error($t('common.failed'));

    }
  });
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

</script>

<template>
  <NModal v-model:open="visible" :title="title"  width="800px"  modal-height="330px">
    <div class="h-300px">
      <SimpleScrollbar>
        <ElForm ref="formRef" :model="model" :rules="rules" label-width="auto">
          <ElRow :gutter="16">

            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.sysConfig.name')" name="name">
                <ElInput v-model="model.name" :placeholder="$t('page.manage.sysConfig.form.name')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem label="Key" name="key">
                <ElInput v-model="model.key" :placeholder="$t('page.manage.sysConfig.form.key')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.sysConfig.value')" name="value">
                <ElInput v-model="model.value" :placeholder="$t('page.manage.sysConfig.form.value')" />
              </ElFormItem>
            </ElCol>

            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.sysConfig.valueEx')" name="valueEx">
                <ElInput v-model="model.valueEx" :placeholder="$t('page.manage.sysConfig.form.valueEx')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.sysConfig.pkey')" name="pkey">
                <ElInput :disabled="props.operateType === 'addChild'" v-model="model.pKey"
                  :placeholder="$t('page.manage.sysConfig.form.pkey')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.sysConfig.groupName')" name="groupName">
                <ElInput :disabled="props.operateType === 'addChild'" v-model="model.groupName"
                  :placeholder="$t('page.manage.sysConfig.form.groupName')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.sysConfig.sort')" name="sort">
                <ElInputNumber v-model="(model.sort as number)" class="w-full"
                  :placeholder="$t('page.manage.sysConfig.form.sort')" />
              </ElFormItem>
            </ElCol>
            <ElCol :lg="12" :xs="24">
              <ElFormItem :label="$t('page.manage.common.isEnable')" name="isEnable">
                <ElRadioGroup v-model="model.isEnable">
                  <ElRadio :value="true">{{ $t('common.yesOrNo.yes') }}</ElRadio>
                  <ElRadio :value="false">{{ $t('common.yesOrNo.no') }}</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol :lg="24" :xs="24">
              <ElFormItem  :label="$t('page.manage.common.remark')" name="remark">
                <ElInput type="textarea" v-model="model.remark" :auto-size="{ minRows: 2, maxRows: 5 }" />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </SimpleScrollbar>
    </div>
    <template #footer>
      <ElSpace justify="end" :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
